package com.sfx.concurrent.demo.concurrent.visibility;

import lombok.extern.slf4j.Slf4j;

/**
 * 对两阶段终止模式进行改进-->使用boolean共享变量stop->要避免可见性加上volatile
 */
@Slf4j(topic = "c.interruptTestDemo")
public class interrupt2 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);//3s后打断
        log.debug("停止监控");
        tpt.stop();
    }
}
//两阶段终止模式
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination{
    private Thread monitor;//监控线程
    private volatile boolean stop = false;
    //启动线程
    public void start(){
        //监控线程
        monitor = new Thread(()->{
            while(true){
                //获取打断标记
                Thread current = Thread.currentThread();//执行监控记录的线程
                if(stop){//不会清除打断标记  interrupted静态方法会清楚打断标记
                    //如果被打断,料理完后事,就退出循环
                    log.debug("料理完后事,就退出循环!!!");
                    break;
                }
                //没有被打断,就睡眠1s之后,进行监控记录
                try {
                    Thread.sleep(1000);//可能被打断->触发异常进入catch块
                    log.debug("current : 执行监控记录");//可能被打断->打断标记为true下次不进入循环
                } catch (InterruptedException e) {
                }
            }
        },"monitor");
        //启动监控线程
        monitor.start();
    }
    //终止线程
    public void stop(){
        stop = true;
        monitor.interrupt();//设置打断标记
    }
}